class StocksController < ApplicationController
  def index
    @stocks = Stock.all
    @stock = Stock.new

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @stocks }
    end
  end

  def show
    @stock = Stock.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @stock }
    end
  end

  def new
    @stock = Stock.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @stock }
    end
  end

  def edit
    @stock = Stock.find(params[:id])
  end

  def create
    @stock = Stock.new(params[:stock])
    @stocks = Stock.all
    @stock.build_transaction(:amount=> @stock.total_purchase_cost, :on_date => @stock.purchase_date, :person_id => @stock.person_id)
    #@stock.transaction.build(:amount => @stock.total_purchase_cost, :person_id => @stock.person)

    respond_to do |format|
      if @stock.save

        @stock = Stock.new
        format.html { render action: "index", notice: 'Stock was successfully created.' }
        format.json { render json: @stock, status: :created, location: @stock }
      else
        format.html { render action: "index" }
        format.json { render json: @stock.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    @stock = Stock.find(params[:id])

    respond_to do |format|
      if @stock.update_attributes(params[:stock])
        format.html { redirect_to @stock, notice: 'Stock was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @stock.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @stock = Stock.find(params[:id])
    @stock.destroy

    respond_to do |format|
      format.html { redirect_to stocks_url }
      format.json { head :no_content }
    end
  end
end
